public class Offer_26 {
    /**
     * 剑指 Offer 26. 树的子结构
     * 输入两棵二叉树A和B，判断B是不是A的子结构。(约定空树不是任意一个树的子结构)
     * <p>
     * <p>
     * B是A的子结构， 即 A中有出现和B相同的结构和节点值。
     */
    public static boolean isSubStructure(TreeNode A, TreeNode B) {
        if (A == null || B == null)
            return false;
        if (recur(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B)) {
            return true;
        } else {
            return false;
        }
    }

    static boolean recur(TreeNode a, TreeNode b) {
        if (b == null) {
            return true;
        }
        if (a == null || a.val != b.val) {
            return false;
        } else {
            return recur(a.left, b.left) && recur(a.right, b.right);
        }
    }

    public static void main(String[] args) {
        TreeNode treeNode1 = new TreeNode(3);
        TreeNode treeNode2 = new TreeNode(4);
        TreeNode treeNode3 = new TreeNode(5);
        TreeNode treeNode4 = new TreeNode(1);
        TreeNode treeNode5 = new TreeNode(2);

        treeNode1.left = treeNode2;
        treeNode1.right = treeNode3;
        treeNode2.left = treeNode4;
        treeNode2.right = treeNode5;

        TreeNode treeNode6 = new TreeNode(4);
        TreeNode treeNode7 = new TreeNode(1);
        treeNode6.left = treeNode7;
        System.out.println(isSubStructure(treeNode1, treeNode6));
    }
}
